/**
 * @param {Egg.Application} app - egg application
 */

async function authentication(ctx, next) {
  if (ctx.session.user && ctx.session.user.userid) {
    await next();
  } else if (ctx.headers.accept.indexOf('text/html') >= 0) {
    ctx.redirect('/login');
  } else {
    ctx.throwError({
      code: 100012,
      msg: '用户没登录',
    });
  }
}

module.exports = (app) => {
  const { router, controller } = app;
  // const apiRouter = router.prefix('/api');
  // const mediaRouter = apiRouter.prefix('/media');
  router.post('/api/media/upload', controller.media.upload);
  router.get('/web/media/:filename', controller.media.show);


  router.post('/api/user/register', controller.user.register);
  router.post('/api/user/login', controller.user.login);
  router.get('/api/user/active', controller.user.active);


  router.post('/api/social/publish', authentication, controller.social.publish);
  router.get('/api/social/article/list', authentication, controller.social.articleList);
  router.get('/api/social/article/:id', authentication, controller.social.articleDetail);
  router.post('/api/social/like', authentication, controller.social.like);
  router.post('/api/social/comment', authentication, controller.social.comment);
  router.get('/api/social/comment', authentication, controller.social.queryComments);
  router.get('/api/user/userinfo', authentication, controller.user.userinfo);
  router.post('/api/user/userinfo', authentication, controller.user.changeUser);

  router.get('/logout', controller.user.logout);
  router.get('/login', controller.home.login);
  router.get('/register', controller.home.login);

  // 放最后，模板渲染
  router.get('*', authentication, controller.home.render);
};
